<template>
	<view class="tabContent">
		<u-navbar title="模块" :fixed="false" :autoBack="false" leftIcon="" :safeAreaInsetTop="true">
		</u-navbar>

		<view class="flex-auto">
			<view class="commonPadding" style="background-color: #fff;">
				<u-swiper :list="list1" height="260rpx" :interval="6000" circular imgMode="scaleToFill">
				</u-swiper>
			</view>
			<u-sticky bgColor="#fff">
				<u-tabs lineColor="#51d0d0" :activeStyle="{
					color:'#51d0d0',
					fontWeight:'500',
					transform:'scale(1.05)'
					}" :list="moduleTypes" :current="currModuleType" @change="switchModuleType">
					<view slot="right" class="x-ec" style="padding-right: 10rpx;">
						<view class="f-dc" style="min-width: 36px;font-size: 12px;text-align: center;color: #999;">
							<text>是否自启</text>
							<text>历史模块</text>
						</view>

						<switch :checked="ActiveModuleStartType" @change="switchChange" color="#1cd842"
							style="zoom: 0.8;">
						</switch>
					</view>
				</u-tabs>
			</u-sticky>
			<view class="common_Box">

				<view class="commonPadding">
					<view style="padding: 10px 10px;">
						<uni-row class="CommonBox" :gutter="20" v-if="currModules.length">
							<uni-col v-for="(module,index) in currModules" :key="index" :span="8" :xs="{span: 8}"
								:sm="{span: 4}" :lg="{span: 3}">
								<view class="CommonCard f-dc" style="position: relative;" @click="initModule(module)">
									<uni-icons fontFamily="CustomFontPlatform"
										style="position: absolute;top: 10rpx;left: 10px;"
										:color="module.Colour || '#51d0d0'"
										size="30rpx">{{$utils.toUniCode(module.ImageUrl || '&#xe6e9;')}}
									</uni-icons>

									<view style="text-align: center;margin-top: 10px;font-size: 24rpx;">
										<text
											style="letter-spacing: 1px;text-shadow: 1px 1px 2px #fff, 2px 2px 2px #d8d8d8;color: #515151;">{{module.ModuleName}}</text>
									</view>
								</view>
							</uni-col>
						</uni-row>

						<u-empty v-else mode="list" icon="/static/Image/Img/noMore.png" iconSize="120" text="已全部开通">
						</u-empty>
					</view>

				</view>
			</view>


		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modules: [],
				currModules: [], // 当前模块列表
				openModules: [], // 已开通模块列表
				closeModules: [], // 未开通模块列表
				moduleTypes: [], // 模块分类
				currModuleType: 0, // 当前模块分类
				list1: [
					'../../static/image/Img/pp.png',
					'../../static/image/Img/p1.png',
					'../../static/image/Img/p2.png',
				],
				enabledSubmitBtn: true, // 防止按钮重复点击
			}
		},
		computed: {
			ActiveModuleStartType() {
				return this.$store.state.appConfigInfo.ActiveModuleStartType
			},
			APPModules() {
				return this.$store.state.appConfigInfo.APPModules;
			},
		},
		watch: {
			enabledSubmitBtn(nval) {
				if (!nval) {
					this.$utils.showLoading("正在加载模块");
				} else {
					this.$utils.hideLoading();
				}
			}
		},
		created() {
			let that = this;
			that.initModuleTypes();
		},
		mounted() {
			let that = this;
			uni.$on('refreshCenter', function(ret) {
				that.initModuleTypes();
			});
		},
		methods: {
			// 初始化模块分类
			initModuleTypes() {
				let that = this;
				that.modules = that.APPModules;
				console.log(that.modules);
				if (that.$utils.isEmpty(that.APPModules)) {
					return;
				}
				that.openModules = that.modules.filter(module => module.Available == 1);
				that.closeModules = that.modules.filter(module => module.Available == 0);
				let openNums = that.openModules.length;
				let closeNums = that.closeModules.length;
				that.moduleTypes = [{
					name: '已开通',
					badge: {
						value: openNums
					}
				}, {
					name: '未开通',
					badge: {
						value: closeNums
					}
				}];
				that.currModules = that.openModules;
			},

			// 切换模块分类
			switchModuleType(item) {
				let that = this;
				that.currModuleType = item.index;
				if (item.index == 0) {
					that.currModules = that.openModules;
				} else {
					that.currModules = that.closeModules;
				}
			},
			switchChange(e) { // 自启历史模块设置
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'appConfigInfo.ActiveModuleStartType',
					data: e.detail.value,
					StorageName: 'ActiveModuleStartType',
					StorageData: JSON.stringify(e.detail.value),
				});
			},

			// 申请开通模块
			applyModule(module) {
				console.log(module);
			},

			// 初始化模块页面
			initModule(module) {
				console.log(module);
				let that = this;
				// 防止按钮重复点击
				if (!that.enabledSubmitBtn) {
					return;
				}
				that.enabledSubmitBtn = false;

				if (that.currModuleType == 1) {
					return this.$utils.msg("已申请开通");
				}

				this.Request.request('getAPPModulePages', {
					UserID: this.$store.state.UserInfo.UserID,
					APPType: module.ModuleID,
				}, (ret) => {
					if (ret.status == 200) {
						const data = ret.data.ds;
						const ds1 = ret.data.ds1;

						// 预先处理ds1，以APPFunID为键，值为对应的数组  
						const ds1Map = new Map(ds1.map(row => [row.APPFunID, [row]]).reduce((acc, [key, val]) => {
							acc.set(key, [...acc.get(key) || [], ...val]);
							return acc;
						}, new Map()));

						let organizedData = that.organizeByTreeTypeName(data, ds1Map);
						organizedData = organizedData.sort((a, b) => a.TreeType - b.TreeType);

						// 这里获取了模块以及页面的权限树，将 IsTabbar 为true的筛选出来，作为底部栏数据

						let TabbarData = organizedData.flatMap(item => item.Node.filter(row => row.IsTabbar)).sort(
							(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序

						uni.removeStorageSync('ModuleInfo_All');
						uni.removeStorageSync('Module_Tabbar');


						// 模块数据持久化（没什么意义，登录一定会获取一遍）
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.ModuleInfo_All',
							data: organizedData,
							StorageName: 'ModuleInfo_All',
							StorageData: JSON.stringify(organizedData),
						});

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.Module_Tabbar',
							data: TabbarData,
							StorageName: 'Module_Tabbar',
							StorageData: JSON.stringify(TabbarData),
						});

						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.ActiveModule',
							data: module,
							StorageName: 'ActiveModule',
							StorageData: JSON.stringify(module),
						});


						let url = '';
						let homePage = module.authPages.find(item => item.IsHomepage);
						console.log(homePage);
						console.log(module.ModuleID);
						switch (module.ModuleID) {
							case 3:
								uni.navigateTo({
									// url: "/st_qms/index/deviceToLink-test",
									url: "/st_qms/index/basicPage",
									complete() {
										that.enabledSubmitBtn = true;
									}
								})
								break;
							case 2:
							case 6:
							case 10:
							case 12:
							case 13:
								if (homePage && homePage != undefined) {
									console.log(homePage.AP_Link);
									url = homePage.AP_Link; // 设置首页路径							
									uni.navigateTo({
										url: url,
										complete() {
											that.enabledSubmitBtn = true;
										}
									})
								} else {
									that.$utils.msg("当前应用未设置首页!");
									that.enabledSubmitBtn = true;
								}
								break;
							default:
								url = '/commonPage/Module/index?moduleID=' + module.ModuleID + '&index=0';
								uni.navigateTo({
									url: url,
									complete() {
										that.enabledSubmitBtn = true;
									}
								})
								break;
						}
					} else {
						that.enabledSubmitBtn = true;
					}


				}, (err) => {
					// 处理错误  
					that.enabledSubmitBtn = true;
				});
			},

			organizeByTreeTypeName(arr, ds1Map) {
				// 创建一个映射来按TreeType分组数据  
				const groupedData = {};

				arr.forEach((item) => {
					const treeType = item.TreeType;
					const treeTypeName = item.TreeTypeName; // 用于分组的键  

					if (!(treeTypeName in groupedData)) {
						groupedData[treeTypeName] = {
							TreeType: treeType, // 保留TreeType  
							APPType: item.appType, // 保留APPType
							Node: [],
						};
					}

					// 检查ds1Map中是否有匹配的APPFunID  
					if (ds1Map.has(item.APPFunID)) {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: ds1Map.get(item.APPFunID), // 如果需要，直接添加IconApprove  
						});
					} else {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: []
						});
					}
				});

				// 提取分组后的数据为数组，并可能按某种逻辑排序（这里不排序，因为TreeTypeName已经是分组键）  
				const sortedData = Object.entries(groupedData).map(([treeTypeName, group]) => ({
					TreeTypeName: treeTypeName,
					...group, // 展开分组对象，它包含TreeType, APPType, APPFunID, 和 Node 数组  
				}));

				return sortedData;
			}
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 15rpx;
	$v-padding: 20rpx;
	$radius: 10rpx;

	.commonPadding {
		padding: $v-padding $h-padding;

		.CommonCard {
			height: 140rpx;
			background-color: #fff;
			border-radius: 12px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			padding: 15rpx 0;
			margin-bottom: 20rpx;
			box-shadow: 1px 1px 7px -6px #bababa;

			&:active {
				transform: scale(0.98);
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
			}

			&::after {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(81, 208, 208, 0.05);
				opacity: 0;
				transition: opacity 0.3s;
			}

			&:active::after {
				opacity: 1;
				border-radius: 12px;
			}
		}
	}

	.tabContent {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		// padding: $v-padding $h-padding;

		.common_Box {
			flex: 1;
			// overflow: auto;
			display: flex;
			flex-direction: column;
			// padding: $v-padding 0 0;
			margin-bottom: $v-padding;

			.u-tabs {
				padding-bottom: 10rpx;
			}

			.module {
				display: flex;
				justify-content: center;
				align-items: center;
				// height: 80px;
				background-color: #fff;
				padding: 20rpx;
				border-radius: 5px;
				margin-bottom: 10px;

				&-left {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 80rpx;
				}

				&-middle {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: flex-start;
					// max-height: 80px;
					overflow: hidden;
					flex: 1;

					&-title {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						font-weight: 500;
						min-height: 25px;
						line-height: 16px;
						padding: 0 5px;
						color: #044569;
					}

					&-subtitle {
						margin-top: 10rpx;
						padding: 0 5px;
						font-size: 24rpx;
						// height: 55px;
						min-height: 100rpx;
						color: #999;
					}
				}

				&-right {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 80px;
				}
			}

		}
	}
</style>